package cn.yusei.teamTribe.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import cn.yusei.teamTribe.exception.FileNotExistsException;
import cn.yusei.teamTribe.exception.ReadInputStreamException;
import cn.yusei.teamTribe.exception.ReadFileException;
import cn.yusei.teamTribe.exception.WriteByteException;

public class FileByteUtil {

	private static byte[] readAllByteFrom(InputStream in) throws IOException
	{
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		int len = -1;
		byte[] bytes = new byte[1024];
		while((len = in.read(bytes)) != -1)
		{
			byteOut.write(bytes, 0, len);
		}
		in.close();
		return byteOut.toByteArray();
	}
	
	public static byte[] fileToByte(String fileName) throws FileNotExistsException, ReadFileException
	{
		File file = new File(fileName);
		if(!file.exists())
			throw new FileNotExistsException("文件 [" + fileName + "] 不存在");
		byte[] bytes = null;
		try
		{
			bytes = readAllByteFrom(new FileInputStream(fileName));
		}
		catch (IOException e)
		{
			e.printStackTrace();
			throw new ReadFileException("读取文件 [" + fileName + "] 失败");
		}
		return bytes;
	}
	
	private static void byteToFile(String fileName, byte[] bytes) throws WriteByteException
	{
		try
		{
			File file = new File(fileName);
			if(!file.getParentFile().exists())
				file.getParentFile().mkdirs();
			FileOutputStream fileOut = new FileOutputStream(fileName);
			fileOut.write(bytes);
			fileOut.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
			throw new WriteByteException("写入文件 [" + fileName + "] 失败");
		}
	}
	
	public static void inputStreamToFile(String fileName, InputStream in) throws ReadInputStreamException, WriteByteException
	{
		byte[] bytes = null;
		try
		{
			bytes = readAllByteFrom(in);
		}
		catch (IOException e)
		{
			e.printStackTrace();
			throw new ReadInputStreamException("从输入流读取文件 [" + fileName + "] 失败");
		}
		try
		{
//			System.out.println(fileName);
			byteToFile(fileName, bytes);
		}
		catch (WriteByteException e)
		{
			e.printStackTrace();
			throw new WriteByteException("写入文件 [" + fileName + "] 失败");
		}
	}
}
